package com.whately.core.base.fileupload.fdfs;

import com.alibaba.fastjson.JSON;
import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.fileupload.constants.DfsConst;
import com.whately.core.base.fileupload.vo.UploadFileRespVO;
import com.whately.core.base.model.ApiResponse;
import com.whately.core.base.utils.http.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

@Component
@Slf4j
public class FdfsFileUploadHelper {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    //http://0.0.0.0:xxx/fs
    //http://0.0.0.0:xxx/fs/api/?method=whately.support.fs.fastdfs.upload
    @Value("${support.fs.store.server:http://0.0.0.0:8883/fs}")
    private String serverUrl;


    @Value("${support.fs.store.accessKey:}")
    private String accessKey;



    /**
     * 上传
     * 文件上传 必须指定enctype="multipart/form-data"
     */
    public UploadFileRespVO fdfsUpload(MultipartFile file){

        String url = serverUrl+"/api";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        ByteArrayResource fileAsResource = null;
        try{
            fileAsResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }

                @Override
                public long contentLength() {
                    return file.getSize();
                }
            };
        }catch (Exception e){
            log.error("fdfsUpload ByteArrayResource error",e);
            throw new ServiceException(400,"文件内容错误");
        }


        MultiValueMap map = new LinkedMultiValueMap();
        map.add("method", DfsConst.fdfs_upload_api_method_name);
        map.add("accessKey",accessKey);
        map.add("file",fileAsResource);

        ApiResponse response = restTemplateUtil.postForObject(url,map, ApiResponse.class,headers);
        if(ApiResponse.isCorrectResponse(response)){
            if(response.getData()==null){
                return null;
            }else{
                UploadFileRespVO vo = JSON.parseObject(JSON.toJSONString(response.getData()), UploadFileRespVO.class);
                return vo;
            }
        }else{
            throw new ServiceException(400,"上传文件失败");
        }
    }

}
